use warnings;
use strict;

sub ImdbApi {
	my ($tt, $title, $edit, $re) = @_ ;
	my $record;
	my $errors = '';
	
	# fix lookup needs separate title and year
	my $year='';
	# $title may not include year
	my $short_title = $title; 
	# if it does
	if ($title =~ m!^(.+) (\d+)$!){ $short_title = $1; $year = $2; }
	
	
	# check for existing record - always needed in case no incomming tt
	open (RDB, "<$VAR{'DataDir'}/ppweb_imdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_imdb.txt, $! (LI01)", 1, 0);
	while (<RDB>){
		if ($tt and m!^$tt [^\t]+\t(.+)!){
			$record = "$1\n";
			&Print ("Cached OMDb record found for: $title (LI01)", 4, 0);
			last;
		}
		# allow for listing title w/ or w/o year
		elsif ($title and m!^(tt\d+) $title(?:[^\t]+)?\t(.+)!){
			$tt = $1;
			$record = "$2\n";
			&Print ("Cached OMDb record found for: $title (LI01)", 4, 0);
			last;
		}
	}
	close RDB or warn $!;
	
	# get new or updated record
	if (!$record or $edit eq 'up'){ # don't enter if edit eq del or fixhttp://www.omdbapi.com/
		#&Print ("Fetching OMDb record: $title (LI02)", 4, 0);
		require LWP::UserAgent;
		my $user_agent = LWP::UserAgent->new;
		$user_agent->agent("Mozilla/8.1");
		my $url;
# 		if ($tt){ $url = "http://imdbapi.com/?i=$tt&plot=full&tomatoes=true"; }
# 		elsif ($short_title and $year){ $url = "http://imdbapi.com/?t=$short_title&y=$year&plot=full&tomatoes=true"; }
		if ($tt){ $url = "http://omdbapi.com/?i=$tt&plot=full&tomatoes=true"; }
		elsif ($short_title and $year){ $url = "http://omdbapi.com/?t=$short_title&y=$year&plot=full&tomatoes=true"; }
		# imdbapi doesn't provide multiple returns, not using
		#else { $url = "http://imdbapi.com/?t=$short_title&plot=full&tomatoes=true"; }
		my $image_url;
		my $response = $user_agent->get($url);
		if ($response->is_success and $response->decoded_content =~ m!{"Response":"False","Error":"String or binary data would be truncated.!){
			$response = '';
			if ($tt){ $url = "http://omdbapi.com/?i=$tt&plot=full"; }
			elsif ($short_title and $year){ $url = "http://omdbapi.com/?t=$short_title&y=$year&plot=full"; }
			&Print ('OMDb record fetch failed, retrying w/o &tomatoes=true (LI02)', 5, 0);
			$response = $user_agent->get($url); 
		}
			
		if ($response->is_success and $response->decoded_content) {
			$record = ''; # clear old record for updating
			my $json = $response->decoded_content;
			my $plot;
			$json =~ s![{}]!!g;
# 			if ($json =~ m!^"Response":"False","Error":"String or binary data would be truncated.[\r\n]+The statement has been terminated."!){
# 				$record .= "OMDb Site Error<br>";
# 			}
			if ($json =~ m!^"Response":"False","Error":"([^"]+)"!){
				$errors = "OMDb Site Error: $1";
				&Print ('OMDb record fetch failed for: '.$title.' (LI02)', 3, 0);
# 				my $er = $1;
# 				$er =~ s![\r\n]+(.+)!<br>                     $1!g;
# 				$record .= "OMDb Site Error: $er<br>";
			}
			else {
				my @json = split (/","/, $json);
				foreach (@json){
					s!^"Title":"!Title.....: !;
					s!^Year":"!Year......: !;
					s!^Rated":"!Rated.....: !;
					s!^Released":"!Released..: !;
					s!^Genre":"!Genre.....: !;
					s!^Director":"!Director..: !;
					#s!^Writer":"!Writer....: !;
					s!^Actors":"!Actors....: !;
					s!^Language":"!Language..: !;
					s!^Country":"!Country...: !;
					s!^Awards":"!Awards....: !;
					s!^Metascore":"!Metascore.: !;
					
					#s!^Plot":"!Plot......: !;#s!([^\n]{85,95} )!$1\n!g;
					s!^Runtime":"!Runtime...: !;
					s!^imdbRating":"!Rating....: !;
					s!^imdbVotes":"!Votes.....: !;
					if (m!^Type":"!){
						next;
					}

					if (s!^Poster":"(.+)$!!) { 
						if ($1 ne 'N/A'){ $image_url=$1; }
						next; 
					}
					elsif (s!^imdbID":"(.+)$!!){ $tt=$1; next; }
					elsif (s!^Writer":"(.+)!Writer....: $1!){
						s! \([^)]+\)!!g;
					}
					elsif (m!^Plot":"(.+)!){
						$plot = $1;
						$plot =~ s!([^\n]{55,65} )!$1<br>            !g;
						$plot = "Plot......: $plot<br>";
						next;
					}
					elsif (m!^tomatoConsensus":"(.+)!){
						my $tc = $1;
						$tc =~ s!([^\n]{55,65} )!$1<br>            !g;
						#s!^tomatoConsensus":"!Consensus.: $tc<br>!;
						$record .= "Consensus.: $tc<br>";
						next;					
					}
					elsif (m!^tomatoImage":"!){ next; }
					elsif (m!^Response":"True"!){ next; }
					if ( s!^tomatoMeter":"(.+)!$plot<br>Rotten Tomatoes<br>T_Meter...: $1! ){ $plot = ''; }
					s!^tomatoRating":"!T_Rating..: !;
					s!^tomatoReviews":"!T_Reviews.: !;
					s!^tomatoFresh":"!T_Fresh...: !;
					s!^tomatoRotten":"!T_Rotten..: !;
					s!^tomatoConsensus":"!Consensus.: !; # if no value (above elsif)
					s!^tomatoUserMeter":"!U_Meter...: !;
					s!^tomatoUserRating":"!U_Rating..: !;
					s!^tomatoUserReviews":"!U_Reviews.: !;
					s!^DVD":"!<br>\tDVD.......: !;
					s!^BoxOffice":"!BoxOffice.: !;
					s!^Production":"!Production: !;
					s!^Website":"(.+)!Website...: <A HREF="$1">$1</A>!;
					
					s!^"Response":"False!U_Reviews.: !;
					
					$record .= "$_<br>\t";
				}
				if ($plot){ $record .= $plot; }
				$record =~ s!\t$!!;
				$record = "$tt $title\t$record<br>\t$DateTime[2]\n"; 
				if ($edit eq 'up'){
					local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_imdb.txt");
					while(<>){
						if ($. == 1) { 
							print $record; # new and updated records
							unless (m!^$tt!){ print; } # replaced record on 1st line
						}
						elsif (m!^$tt!){ next; } # replaced record elsewhere
						else { print; }
					}
				}
				else {
					open (WDB, ">>$VAR{'DataDir'}/ppweb_imdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_imdb.txt, $! (LI02)", 1, 0);
						print WDB $record;
					close WDB or warn $!;
				}
				$record =~ s!^[^\t]+\t!!; # remove leading id and title
				if ($edit eq 'up'){ $record = "Record Updated\n\n$record"; }
				&Print ('OMDb record fetch successful for: '.$title.' (LI02)', 4, 0);

# 				if ($tt){
# 					local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_imdb.txt");
# 					while(<>){
# 						if ($. == 1) { 
# 							print $record; # new and updated records
# 							unless (m!^$tt!){ print; } # replaced record on 1st line
# 						}
# 						elsif (m!^$tt!){ next; } # replaced record elsewhere
# 						else { print; }
# 					}
# 					$record =~ s!^[^\t]+\t!!; # remove leading id and title
# 					if ($edit eq 'up'){ $record = "Record Updated\n\n$record"; }
# 				}
			}
		}
		else { 
			&Print ('OMDb record fetch failed: '.$response->status_line.' (LI03)', 1, 0); 
			$errors .= 'OMDb record fetch failed: '.$response->status_line."\n";
		}
		
		# fetch image, if we don't have one
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){ &Print ('Using cached image (LI05)', 5, 0); }
		elsif ($image_url){# and !-e "$VAR{'PPWebDir'}/images/$tt.jpg"){
			#&Print ("Fetching IMDb image for: $title (LI02)", 4, 0);
			if ($image_url =~ m!jpg$!){
				$response = $user_agent->get($image_url, ':content_file' => "$VAR{'PPWebDir'}/images/$tt.jpg");
				unless ($response->is_success) {
					&Print ('IMDb image fetch failed: '.$response->status_line.' (LI04)', 1, 0);
					$errors .= 'IMDb image fetch failed: '.$response->status_line."\n";
				}
				else { 
					&Print ('IMDb image fetch successful: '.$tt.'.jpg (LI05)', 4, 0);
					my $convert = '';
					if ($convert = `which convert` and $convert =~ m!^/!){
					#if ($VAR{'ImdbApiImages'} eq 'convert'){
						chomp $convert;
						#my $ret = `$convert "$VAR{'PPWebDir'}/images/$tt.jpg" -resize '342>' "$VAR{'PPWebDir'}/images/$tt.tmp"`;
						if (system qx($convert '$VAR{'PPWebDir'}/images/$tt.jpg' -resize '342>' '$VAR{'PPWebDir'}/images/$tt.tmp')){
							&Delete ($VAR{'PPWebDir'}.'/images', $tt.'.jpg', 'LI05');
							&Save ($VAR{'PPWebDir'}.'/images', $tt, 'tmp', $VAR{'PPWebDir'}.'/images', $tt, 'jpg', 'LI05');
							&Print ('  Image resize successful: '.$tt.'.jpg (LI05)', 4, 0);
						}
						#if ($ret){ &Print ('convert returned: $ret (LI05)', 5, 0); }
					}
				}
			}
			# to let me know if not all images are .jpg
			else { &Print ("Image not a jpg: $image_url (LI05)", 1, 0); }
		}
		else { &Print ('No IMDb image available to fetch (LI05)', 4, 0); }
	}

	# delete image
	if ($edit eq 'img'){
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){ 
			&Delete ("$VAR{'PPWebDir'}/images", "$tt.jpg", 'LI07');
		}
	}
	# delete record
	if ($edit eq 'del'){
		if ($edit eq 'del'){
			&Print ("Deleting OMDb record: $title (LI06)", 4, 0);
		}
		local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_imdb.txt");
		while(<>){
			if ($. == 1) { 
				unless (m!^$tt!){ print; } # deleted or replaced record on 1st line
			}
			elsif (m!^$tt! and $edit){ next; } # deleted or replaced record elsewhere
			else { print; }
		}
		#if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){ &Delete ("$VAR{'PPWebDir'}/images", "$tt.jpg", 'LI07'); }
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">Record Deleted</font></pre></td></tr><tr><td>";
	}
	# process record
	elsif ($record){
		# IMDB link
		my $links = "<br>Links.....: <A HREF=\"http://www.imdb.com/title/$tt/\">IMDb</A></B>&nbsp;&nbsp;&nbsp;";
		# Rotten Tomatoes link - if available
		unless ($record =~ m!N/A<br><br>\t[^\t]+$!){
			my $rt = $tt;
			$rt =~ s!^tt(\d+)!<A HREF=\"http://www.rottentomatoes.com/alias?type=imdbid&s=$1\">Rotten Tomatoes</A>&nbsp;&nbsp;&nbsp;!;
			#$record =~ s!Rotten Tomatoes!$rt!;
			$links .= $rt;
		}
		# record update/delete links
		$links .= "Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=limdb&amp;tt=$tt&amp;nt=$title&amp;db=up&amp;re=$re\">update</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=limdb&amp;tt=$tt&amp;nt=$title&amp;db=del&amp;re=$re\">delete</a>&nbsp;Image:&nbsp;<a href=\"$VAR{'DbCgi'}?do=limdb&amp;tt=$tt&amp;nt=$title&amp;db=img&amp;re=$re\">delete</a>";
		# add links to record
		$record =~ s!<br><br>\t([^\t]+)$!\n$links\n\n$1!;
		# replace all tabs and <br>'s with newline
		$record =~ s!<br>\t?!\n!g;
		# add pre container and image - if one exists, and td/tr close/start
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){
			$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tt.jpg\" style=\"float:right\; padding-right:50px;\">\n<pre><font face=\"Monospace,Courier,Courier New\">$record\n</font></pre><br clear=\"all\"></td></tr><tr><td>\n";
		}
		elsif ($record =~ m!"Response":"Parse Error"!){
			$record = "<pre><font face=\"Monospace,Courier,Courier New\">The OMDb site returned a 'Parse Error', try again later.</font></pre></td></tr><tr><td>";
		}
		else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>"; }
	}
	else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">Unable to fetch record\n\n$errors</font></pre></td></tr><tr><td>";}
	
	return $record;
	# other imdb options
	
# 	Name search (json): http://www.imdb.com/xml/find?json=1&nr=1&nm=on&q=jeniffer+garner
# 	Title search (xml): http://www.imdb.com/xml/find?xml=1&nr=1&tt=on&q=lost
# 	
# 	http://app.imdb.com/find?api=v1&appid=iphone1&locale=en_US&q=shrek
# 	It looks like all you need is q. 
}

1;